package tool;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import java.util.HashMap;

public class CustomSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession sess = httpSessionEvent.getSession();
        System.out.println("创建会话，id为" + sess.getId());
        // 设置会话的最大无效间隔，单位为秒
        sess.setMaxInactiveInterval(5);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession sess = httpSessionEvent.getSession();
        ServletContext app = sess.getServletContext();
        String name = (String) sess.getAttribute("name");
        String sessId = sess.getId();
        @SuppressWarnings("unchecked")
        HashMap<String, String> users = (HashMap<String, String>) app.getAttribute("users");
        // 如果users中包含sessId
        if (users.containsValue(sessId)) {
            users.remove(name, sessId);
            // 更新users
            app.setAttribute("users", users);
            app.setAttribute("online", (int) app.getAttribute("online") - 1);
            System.out.println("id为" + sess.getId() + "的会话即将失效，已将大厅用户数减少1人");
        }
        System.out.println("销毁会话，id为" + sess.getId());
    }
}
